﻿using Microsoft.AspNetCore.Mvc;
using Material.Mvc.Models;
using Material.Mvc.Services;
using System.Text.Json;

namespace Material.Mvc.Controllers
{
    public class WeatherController : Controller
    {
        private readonly IWeatherService _weatherService;
        private readonly ILogger<WeatherController> _logger;
        private readonly IConfiguration _configuration;

        public WeatherController(IWeatherService weatherService, ILogger<WeatherController> logger, IConfiguration configuration)
        {
            _weatherService = weatherService;
            _logger = logger;
            _configuration = configuration;
        }

        public async Task<IActionResult> Index()
        {
            var viewModel = new WeatherViewModel();
            
            try
            {
                // 获取保存的位置
                viewModel.SavedLocations = await _weatherService.GetSavedLocationsAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取保存位置时发生错误");
                viewModel.SavedLocations = new List<LocationCoordinate>();
            }

            return View(viewModel);
        }

        public IActionResult Test()
        {
            return View();
        }

        public IActionResult CssTest()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> GetWeather([FromBody] WeatherRequest request)
        {
            try
            {
                if (request == null || request.Latitude == 0 || request.Longitude == 0)
                {
                    return BadRequest(new { success = false, message = "经纬度不能为空" });
                }

                var weatherResponse = await _weatherService.GetWeatherAsync(request.Latitude, request.Longitude);
                
                if (weatherResponse.Success)
                {
                    return Json(new { success = true, data = weatherResponse.Data });
                }
                else
                {
                    return Json(new { success = false, message = weatherResponse.Message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气数据时发生错误");
                return Json(new { success = false, message = "获取天气数据失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> SaveLocation([FromBody] LocationCoordinate location)
        {
            try
            {
                if (location == null || string.IsNullOrEmpty(location.Name))
                {
                    return BadRequest(new { success = false, message = "位置信息不完整" });
                }

                location.CreatedAt = DateTime.Now;
                var result = await _weatherService.SaveLocationAsync(location);
                
                if (result)
                {
                    return Json(new { success = true, message = "位置保存成功" });
                }
                else
                {
                    return Json(new { success = false, message = "位置保存失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存位置时发生错误");
                return Json(new { success = false, message = "保存位置失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> DeleteLocation([FromBody] DeleteLocationRequest request)
        {
            try
            {
                if (request?.Id <= 0)
                {
                    return BadRequest(new { success = false, message = "无效的位置ID" });
                }

                var result = await _weatherService.DeleteLocationAsync(request.Id);
                
                if (result)
                {
                    return Json(new { success = true, message = "位置删除成功" });
                }
                else
                {
                    return Json(new { success = false, message = "位置删除失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除位置时发生错误");
                return Json(new { success = false, message = "删除位置失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> GetLocationName([FromBody] WeatherRequest request)
        {
            try
            {
                if (request == null || request.Latitude == 0 || request.Longitude == 0)
                {
                    return BadRequest(new { success = false, message = "经纬度不能为空" });
                }

                // 使用OpenWeatherMap的Geocoding API获取地区名称
                var locationName = await GetLocationNameFromCoordinates(request.Latitude, request.Longitude);
                
                return Json(new { success = true, locationName = locationName });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取地区名称时发生错误");
                return Json(new { success = false, message = "获取地区名称失败" });
            }
        }

        private async Task<string> GetLocationNameFromCoordinates(double latitude, double longitude)
        {
            try
            {
                var apiKey = _configuration["OpenWeatherMap:ApiKey"];
                var url = $"http://api.openweathermap.org/geo/1.0/reverse?lat={latitude}&lon={longitude}&limit=1&appid={apiKey}";
                
                using var client = new HttpClient();
                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    using var doc = JsonDocument.Parse(content);
                    var root = doc.RootElement;
                    
                    if (root.GetArrayLength() > 0)
                    {
                        var location = root[0];
                        var name = location.GetProperty("name").GetString();
                        var country = location.GetProperty("country").GetString();
                        var state = location.GetProperty("state").GetString();
                        
                        // 构建地区名称：城市名, 省份, 国家
                        var locationName = name;
                        if (!string.IsNullOrEmpty(state) && state != name)
                        {
                            locationName += $", {state}";
                        }
                        if (!string.IsNullOrEmpty(country))
                        {
                            locationName += $", {country}";
                        }
                        
                        return locationName;
                    }
                }
                
                // 如果无法获取地区名称，返回坐标
                return $"纬度: {latitude:F4}, 经度: {longitude:F4}";
            }
            catch
            {
                // 如果出错，返回坐标
                return $"纬度: {latitude:F4}, 经度: {longitude:F4}";
            }
        }
    }

    public class WeatherRequest
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }

    public class DeleteLocationRequest
    {
        public int Id { get; set; }
    }


}
